<template>
  <el-container>
      <el-header>
        <div class="report_header" ref="headerHeight">
          <div class="report_header_left"></div>
          <!-- <div style="width: 300px;display: flex;align-items: center;margin-left: 10px;">
            <svg-icon class="primary" :icon-class="$route.meta.icon"/>
            <span style="margin-left: 5px;" class="primary">{{$route.meta.title}}</span>
          </div> -->
          <div class="report_header_left"></div>
          <div class="report_header_query">
            <el-select v-model="query.status" clearable  placeholder="请选择状态">
              <el-option label="全部" value=""></el-option>
              <el-option label="启用" value="1"></el-option>
              <el-option label="停用" value="0"></el-option>
            </el-select>
          </div>
          <div style="display: flex;flex-direction: row;justify-content:flex-end;width: 100%;">
            <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px">
              <div class="report_header_query">
                <el-input prefix-icon="el-icon-search" placeholder="用户账号"  v-model="query.username"></el-input>
              </div>
              <div class="report_header_query">
                <el-input prefix-icon="el-icon-search" placeholder="姓名" v-model="query.nickname"></el-input>
              </div>
            </div>
            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary"  @click="querySysUser">查询</el-button>
          </div>
        </div>

<!--        <div>-->
<!--          <svg-icon class="primary" :icon-class="$route.meta.icon"/>-->
<!--          <span class="primary">{{$route.meta.title}}</span>-->
<!--        </div>-->
<!--        <div class="header-button-container">-->
<!--          <el-button :icon="queryType? 'el-icon-search':'el-icon-close'" type="primary"-->
<!--                     @click="chooseClick">{{queryType == false?'隐藏':'查询'}}-->
<!--          </el-button>-->
<!--        </div>-->
      </el-header>
    <div class="pd10">
      <el-table
        :data="sysUserForm"
        border
        stripe
        v-loadMore="[payLoads,'sysUser-list']"
        :height="curHeight"
        style="width: 100%">
        <el-table-column
          type="index"
          width="50"
          align="center"
          fixed
        >
        </el-table-column>
        <el-table-column
          label="登录账号"
          width="200"
          align="center"
          prop="username"
        >
        </el-table-column>
        <el-table-column
          label="姓名"
          width="200"
          align="center"
          prop="nickname"
        >
        </el-table-column>
        <el-table-column
          label="部门"
          width="200"
          align="center"
          prop="officeName"
        >
        </el-table-column>
        <el-table-column
          label="手机号码"
          width="200"
          align="center"
          prop="mobile"
        >
        </el-table-column>

        <el-table-column
          label="绑定角色"
          width="200"
          align="center"
          prop="roleName"
        >
        <template slot-scope="scope">
          {{scope.row.roleName | watchRoleName}}
        </template>
        </el-table-column>

        <el-table-column
          label="微信"
          width="200"
          align="center"
          prop="wxId"
        >
          <template  slot-scope="scope">
            <span>{{scope.row.wxId? '已绑定': '未绑定'}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="用户备注"
          width="350"
          align="left"
          prop="remark"
        >
        </el-table-column>
        <el-table-column
          label="状态"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == 0?'info':'success'">
              <span>{{scope.row.status | watchStatus}}</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="功能"

          prop="remark"
          width="330"
          fixed="right"
        >
<!--        <template slot-scope="scope">-->
<!--          <el-tooltip v-permission="['sysUser.edit']" class="item" effect="dark" content="启用或停用" placement="top-start">-->
<!--            &lt;!&ndash; <el-button @click="openClick(scope.row)" :type="scope.row.status == 0? 'primary': 'warning'" size="mini">{{scope.row.status == 0?'启用':'停用'}}</el-button> &ndash;&gt;-->
<!--            <el-button @click="openClick(scope.row)" :loading="scope.row.openLoading" type="primary" size="mini">{{scope.row.status == 0?'启用':'停用'}}</el-button>-->
<!--          </el-tooltip>-->
<!--          <el-tooltip v-permission="['sysUser.edit']" class="item" effect="dark" content="权限设置" placement="top-start">-->
<!--            <el-button @click="editClick(scope.row)" type="primary" size="mini">授权</el-button>-->
<!--          </el-tooltip>-->
<!--          <el-tooltip v-permission="['sysUser.edit']" class="item" effect="dark" content="邀请" placement="top-start">-->
<!--            <el-button @click="bindingUser(scope.row)" type="primary" size="mini">邀请</el-button>-->
<!--          </el-tooltip>-->
<!--          <el-tooltip v-permission="['sysUser.edit']" class="item" effect="dark" content="重置密码" placement="top-start">-->
<!--            <el-button @click="resetPwd(scope.row)" :loading="scope.row.pwdLoading" type="danger" size="mini">重置密码</el-button>-->
<!--          </el-tooltip>-->
<!--        </template>-->
<!--        </el-table-column>-->
          <template slot-scope="scope">
            <el-tooltip  class="item" effect="dark" v-permission="['sysUser.edit']" content="启用或停用" placement="top-start">
              <!-- <el-button @click="openClick(scope.row)" :type="scope.row.status == 0? 'primary': 'warning'" size="mini">{{scope.row.status == 0?'启用':'停用'}}</el-button> -->
              <el-button @click="openClick(scope.row)" :loading="scope.row.openLoading" type="primary" size="mini">{{scope.row.status == 0?'启用':'停用'}}</el-button>
            </el-tooltip>
            <el-tooltip  class="item" effect="dark" v-permission="['sysUser.edit']" content="权限设置" placement="top-start">
              <el-button @click="editClick(scope.row)" type="primary" size="mini">授权</el-button>
            </el-tooltip>
<!--            <el-tooltip  class="item" effect="dark" v-permission="['sysUser.edit']" content="邀请" placement="top-start">-->
<!--              <el-button @click="bindingUser(scope.row)" type="primary" size="mini">邀请</el-button>-->
<!--            </el-tooltip>-->
            <el-tooltip  class="item" effect="dark" v-permission="['sysUser.edit']" content="重置密码" placement="top-start">
              <el-button @click="resetPwd(scope.row)" :loading="scope.row.pwdLoading" type="danger" size="mini">重置密码</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="40">
          <template slot-scope="scope">
          <div>
            <el-tooltip v-permission="['sysUser.del']" class="item" effect="dark" content="删除" placement="top-start">
              <a @click="deleteSysUser(scope.row)">
                <i style="color: #F56C6C" class="el-icon-delete"></i>
              </a>
            </el-tooltip>
          </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-footer class="el-footerBox">
      <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                  @pagination="loadSysUser"></pagination>
    </el-footer>

    <el-dialog title="用户授权" :visible.sync="dialogFormVisible" :time="times">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="角色权限" name="first">
          <el-table
            ref="multipleTable"
            :data="roleData"
            tooltip-effect="dark"
            style="width: 100%"
            border
            height="300px"
            @selection-change="formClick"
          >
            <el-table-column
              type="selection"
              width="55"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="name"
              label="角色名字"
              width="200"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="remark"
              label="角色说明"
              show-overflow-tooltip>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="部门权限" name="second">
          <div style="padding: 20px;border: 1px solid #DCDFE6;border-radius: 3px;height: 300px;overflow: auto">
            <el-tree highlight-current :data="data" show-checkbox  :default-expand-all="show_header"
                     :props="defaultProps" node-key="id" ref="tree"
                     @check-change="treeClick">
            <span class="slot-t-node" slot-scope="{ node, data }">
                <i :class="{'el-icon-office-building primary': data.type==0, 'el-icon-school':data.type==1}"/>
                <span>{{ data.name }}</span>
            </span>
            </el-tree>
          </div>
        </el-tab-pane>

      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="editClicked" @click="updateSysUser">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
          title="提示"
          :visible.sync="bindingShow"
            width="30%"
          center>
          <div style="display: flex; flex-direction: column; justify-content: center; align-items: center;font-size: 15px; line-height: 30px;">
            <span>微信扫一扫分享链接 或</span>
            <span>复制邀请链接邀请绑定员工</span>
            <img :src="bindingImage" alt="" style="width: 150px; height: 150px; margin: 20px 0;">
            <el-link type="primary" @click="CopyCode">复制邀请链接</el-link>
          </div>
          <span slot="footer" class="dialog-footer"></span>
    </el-dialog>
  </el-container>
</template>
<script>
  import loadMore from '@/utils/loadMore.js'
  import permission from '@/directive/permission/index.js' // 权限判断指令
  import {list, del, update, updateScopes, find, resetPwd} from '@/api/sysUser'
  import {list as officeList} from '@/api/sysOffice'
  import {list as roleList} from '@/api/sysRole'
  import utils from '../../utils/utils.js'
  import Pagination from '@/components/Pagination';
  import {mapGetters} from 'vuex'
  export default {
    name: 'sysUser-list',
    directives: { permission,loadMore },
    activated() {
      this.payLoads = new Date().getTime();
    },
    computed: {
        ...mapGetters([
            'mchId'
        ])
    },
    data() {
      return {
        payLoads:'',
        times:'',
        sysUserForm: [],
        pageNum: 1,
        pageSize: 20,
        total: 0,
        queryType: true,
        query: {
          nickname: '',
          status: '',
          username:''
        },
        keyword:{
          nickname: '',
          status: '',
          username:''
        },
        sysUserOpenForm: {
          id: '',
          status: '',
        },
        dialogFormVisible: false,
        activeName: 'first',
        roleData: [],
        // shops:[],
        // shopData:[],
        show_header: true,
        data: [],
        defaultProps: {
          children: 'childrens',
          label: 'name'
        },
        roles: [],
        offices: [],
        userId: '',
        curHeight:null,
        bindingShow: false,
        bindingImage: '',
        editClicked: false
      }
    },
    components: {Pagination},
    created() {
      this.times=new Date().getSeconds()
      this.loadSysUser()
      this.officeList();
      // this.loadShop()
    },
    filters: {
      watchStatus(val) {
        if (val == 1) {
          return '启用'
        } else {
          return '停用'
        }
      },
      watchRoleName(val) {
        if (val.length>0){
          let newVal = ''
          for (var i = 0; i < val.length; i++) {
            if(newVal !== '')
              newVal = newVal +"；"
            newVal = newVal + String.fromCharCode(65+i)+'.' + val[i] + ' ' ;
          }
          return newVal
        }else {
          return ''
        }
      },
    },
    mounted(){
      this.comeIn()
      this.beforeMount();
    },
    methods: {
      beforeMount() {
        var _this = this
        window.onresize = () => {
          return (() => {
            if (this.queryType == false) {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 266//减去页面上固定高度height
            } else {
              var h = document.documentElement.clientHeight || document.body.clientHeight;
              _this.curHeight = h - 220//减去页面上固定高度height
            }
          })();
        };
      },
      comeIn(){
        console.log('222')
        var h = document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220//减去页面上固定高度height
      },
      editClick(row) {
        var _this  =this
        this.roleList();
        this.userId = row.id;
        this.dialogFormVisible = true
        this.times=new Date().getSeconds()
        setTimeout(function () {
          _this.findSysUser()
        },1000)

      },
      openClick(row) {
        var _this = this
        row.openLoading = true
        console.log(row);
        this.sysUserOpenForm.id = row.id;
        if (row.status == 0) {
          this.sysUserOpenForm.status = 1
        } else if (row.status == 1) {
          this.sysUserOpenForm.status = 0
        }
        this.sysUserOpenForm.status = parseInt(this.sysUserOpenForm.status);
        update(_this.sysUserOpenForm).then(response => {
          console.log(response)
          _this.sysUserForm.forEach(function (item) {
            if (item.id == row.id){
              item.status = response.data.status
            }
          })
          row.openLoading = false
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          });
        }).catch(error => {
          row.openLoading = false
          console.log('error!!')
        });
      },
      //重置密码的点击事件
      resetPwd(row) {
        var _this = this
        row.pwdLoading = true
        let data = {
          userId:row.id
        }
        resetPwd(data).then(response => {
          console.log(response)
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          });
          row.pwdLoading = false
        }).catch(error => {
          row.pwdLoading = false
          console.log('error!!')
        });
      },
      roleList: function () {
        let _this = this
        let params = new URLSearchParams();
        roleList(params).then(response => {
          console.log(response)
          _this.roleData = response.data.data
        }).catch(error => {
          console.log('error!!')
        });
      },

      officeList() {
        let _this = this;
        let params = new URLSearchParams();
        params.append('menuType', 0);
        officeList(params).then(response => {
          console.log(response)
          _this.data = response.data;
        }).catch(error => {
          console.log('error!!')
        });
      },
      chooseClick() {
        this.queryType = !this.queryType
        if (this.queryType == false) {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 266//减去页面上固定高度height
        } else {
          var h = document.documentElement.clientHeight || document.body.clientHeight;
          this.curHeight = h - 220//减去页面上固定高度height
        }
      },
      deleteSysUser(data) {
        console.log(data)
        var _this = this
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          del(data.id).then(response => {
            console.log(response)
            _this.sysUserForm.forEach(function (item,index) {
              if (item.id == data.id){
                _this.sysUserForm.splice(index,1)
              }
            });
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            });
          }).catch(error => {
            console.log('error!!')
          });
        }).catch(() => {
        });
      },
      querySysUser() {
        this.keyword = this.query;
        this.pageNum = 1
        this.loadSysUser()
      },
      resetSysUser() {
        this.query.nickname = '';
        this.query.status = '';
        this.query.username = '';
        this.keyword = this.query;
        this.pageNum = 1;
        this.loadSysUser()
      },
      loadSysUser() {
        var _this = this
        // var roleName = ""
        let params = new URLSearchParams();
        params.append('pageNum', _this.pageNum);
        params.append('pageSize', _this.pageSize);
        params.append('status', _this.keyword.status);
        params.append('nickname', _this.keyword.nickname);
        params.append('username',_this.keyword.username)
        list(params).then(response => {
          response.data.data.map(item => {
            item.openLoading = false
            item.pwdLoading = false
            return item
          })
          _this.sysUserForm = response.data.data
          _this.total = response.data.total
        }).catch(error => {
          console.log('error!!')
        });
      },
      handleClick(tab, event) {
        console.log(tab, event);
        },
      formClick(val) {
        var _this = this
        _this.roles = [];
        val.forEach(function (item) {
          _this.roles.push(item.id)
        })
      },
      treeClick(data, type) {
        var _this = this
        if (type == true && data.childrens == '') {
          _this.offices.push(data.id)
        } else if (type == false && data.childrens == '') {
          console.log(data)
          _this.offices.forEach(function (item, index) {
            if (item == data.id) {
              _this.offices.splice(index, 1)
            }
          })
        }
      },
      updateSysUser() {
        var _this = this
        this.editClicked = true
        var officeList = []
        var shopList=[]
        _this.offices.forEach(function (item) {
          var item1={
            scopeType:1,
            officeId:item
          }
            officeList.push(item1)
        });
        let params = new URLSearchParams();
        _this.roles.forEach(function (item) {
           params.append('roles', item);
        });
        params.append('userId', _this.userId)
        updateScopes(params,officeList).then(response => {
          _this.dialogFormVisible = false
          _this.loadSysUser()
          _this.$message({
            message: response.content,
            offset: 120,
            center: true
          });
          _this.editClicked = false
        }).catch(error => {
          _this.editClicked = false
        });
      },
      findSysUser() {
        var _this = this
        find(_this.userId).then(response => {
          console.log(response)
          var officeList=[]
          var shopList=[]
          response.data.dataScopeList.forEach(item=>{
            if (item.scopeType==1){
              var off={
                id:item.officeId
              }
              officeList.push(off)
            }else{
              shopList.push(item)
            }
          })
          // console.log(officeList)
          _this.$refs.tree.setCheckedNodes(officeList);
          _this.roleData.forEach(function (item, index) {
            response.data.roleList.forEach(function (findItem) {
              if (item.id == findItem.id) {
                _this.roles.push(item.id);
                _this.$refs.multipleTable.toggleRowSelection(_this.$refs.multipleTable.data[index], true)
              }
            })
          })
        }).catch(error => {
          console.log('error!!')
        });
      },
      bindingUser (data) {
         console.log(data)
          // let code = 'http://10su200.rzico.com/#/binding/user?id=' + data.id
          let code = `http://${this.mchId}.rzico.com/#/binding/user?id=${data.id}`
          this.bindingImage = process.env.VUE_APP_BASE_API + '/zxing/createImage?data=' + encodeURIComponent(code)
          console.log(this.bindingImage)
          this.bindingShow = true

          this.bindingId = data.id
      },
      CopyCode () {
          // let code = 'http://10200.rzico.com/#/binding/user?id=' + this.bindingId
          let code = `http://${this.mchId}.rzico.com/#/binding/user?id=${this.bindingId}`
          let url =  code
          // let url = 'http://10200.rzico.com/#/binding/index?id=' + this.bindingId
          let oInput = document.createElement('input');
          oInput.value = url;
          document.body.appendChild(oInput);
          oInput.select(); // 选择对象;
          console.log(oInput.value)
          document.execCommand("Copy"); // 执行浏览器复制命令
          this.$message({
              message: '复制成功',
              type: 'success'
          });
          oInput.remove()
      }
    }
  }
</script>

<style scoped>
  .el-footerBox {
    height: 50px !important;
    line-height: 50px !important;
    border-top: 1px solid #f2f2f2;
  }
  .el-headerTitle {
    font-size: 20px;
    color: #409EFF;
  }

  /deep/ .el-dialog__body {
    padding: 10px 20px 15px 20px;
  }

  /deep/ .el-dialog__header {
    border: 1px solid #eeeeee !important;
    padding: 15px !important;
  }
  .app {
    background-color: rgba(248, 248, 248, 0.8);
  }

  /deep/.el-header {
    padding: 10px;
    /* height: 100% !important; */
    padding-bottom: 0;
  }

  .report_header {
    width: 100%;
    min-height: 40px;
    box-sizing: border-box;
    background-color: rgba(248, 248, 248, 0.8);
    display: flex;
    align-items: center;
    padding-bottom: 5px;
    position: relative;
    padding-left: 5px;
    padding-right: 5px;
  }
  .report_header_left {
    width: 5px;
    height: 100%;
    background-color: #409EFF;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
  }
  .report_header_date {
    margin-left: 10px;
    width: 250px;
    margin-top: 5px;
  }
  .report_header_query {
    margin-left: 10px;
    width: 180px;
    margin-top: 5px;
  }
</style>
